package com.metaera.app.ui.activities;

import android.graphics.Color;
import android.os.Bundle;

import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import com.jaeger.library.StatusBarUtil;
import com.lxj.xpopup.XPopup;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.SearchHistoryPresenter;
import com.metaera.app.controller.presenter.SearchHotPresenter;
import com.metaera.app.controller.view.SearchHistoryListView;
import com.metaera.app.controller.view.SearchHotListView;

import com.metaera.app.data.network.ApiParam;
import com.metaera.app.ui.adapters.SimpleFragmentStatePagerAdapter;
import com.metaera.app.ui.adapters.navigator.TabCommonNavigatorAdapter;
import com.metaera.app.ui.core.BaseActivity;
import com.metaera.app.ui.fragments.SearchResultListFragment;
import com.metaera.app.ui.fragments.SynthesisSearchResultFragment;
import com.metaera.app.ui.popup.SearchFilterPopup;
import com.metaera.app.utils.TextWatcherAdapter;
import com.metaera.app.utils.event.OnSearchIndexEvent;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Arrays;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

/**
 * 搜索页面
 * <p>
 * 综合，资讯，文章，快讯，专题，专栏作者
 */
public class SearchActivity extends BaseActivity {

    private ViewPager      viewPager;
    private MagicIndicator magicIndicator;
    private View           layoutSearchResult;

    private SearchFilterPopup searchFilterPopup;

    protected void initStatusBar() {
        StatusBarUtil.setColor(this, Color.parseColor("#F9F9F9"), 0);
        StatusBarUtil.setLightMode(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_search_new;
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        // find
        EditText etSearch = findViewById(R.id.et_search);
        Button buttonSearch = findViewById(R.id.button_search);
        viewPager = findViewById(R.id.view_pager);
        magicIndicator = findViewById(R.id.magic_indicator);
        layoutSearchResult = findViewById(R.id.layout_search_result);
        View buttonSearchFilter = findViewById(R.id.button_search_filter);

        TextView buttonClearHistory = findViewById(R.id.button_clear_history);
        RecyclerView searchRecyclerView = findViewById(R.id.hot_search_recycler_view);

        // network 搜索
        SearchHotPresenter searchPresenter = new SearchHotPresenter();
        searchPresenter.setModelAndView(new SearchHotListView(searchRecyclerView));
        searchPresenter.hotSearch();

        // 搜索历史
        SearchHistoryPresenter historyPresenter = new SearchHistoryPresenter();
        historyPresenter.setModelAndView(new SearchHistoryListView(getWindow().getDecorView(), historyPresenter));
        historyPresenter.find();

        // init listener
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());
        buttonClearHistory.setOnClickListener(v -> historyPresenter.clear());
        buttonSearch.setOnClickListener(v -> search(historyPresenter, etSearch));

        searchFilterPopup = new SearchFilterPopup(this, getSupportFragmentManager());
        buttonSearchFilter.setOnClickListener(v ->
                new XPopup.Builder(v.getContext())
                        .enableDrag(false)
                        .asCustom(searchFilterPopup)
                        .show()
        );

        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                search(historyPresenter, etSearch);
                return true;
            }
            return false;
        });

        etSearch.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(@NonNull Editable s) {
                if (TextUtils.isEmpty(s)) {
                    layoutSearchResult.setVisibility(View.GONE);
                }
            }
        });
    }

    private void search(SearchHistoryPresenter presenter, EditText editText) {
        presenter.add(editText.getText());
        if (!TextUtils.isEmpty(editText.getText())) {
            renderSearchList(editText.getText().toString());
            layoutSearchResult.setVisibility(View.VISIBLE);
        }
    }

    public void renderSearchList(String keyword) {
        ArrayList<String> titleList = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.search_types)));
        ArrayList<Fragment> fragmentList = new ArrayList<>();

        for (int i = 0; i < titleList.size(); i++) {
            if (i == 0) {
                fragmentList.add(SynthesisSearchResultFragment
                        .newInstance(keyword, searchFilterPopup.orderType, searchFilterPopup.timeType));

            } else {
                // 1-文章；2-快讯；3-专题；4-专栏；5-活动
                fragmentList.add(SearchResultListFragment
                        .newInstance(keyword, searchFilterPopup.orderType, searchFilterPopup.timeType, i));
            }
        }

        CommonNavigator commonNavigator = new CommonNavigator(viewPager.getContext());
        commonNavigator.setAdapter(new TabCommonNavigatorAdapter(viewPager, titleList));

        // 导航器设置适配器
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewPager);

        viewPager.setAdapter(new SimpleFragmentStatePagerAdapter(getSupportFragmentManager(), fragmentList));
    }

    @Subscribe
    public void event(OnSearchIndexEvent event) {

        viewPager.setCurrentItem(event.index);
    }

}
